<?php

	class FrontAction extends ActionBase{
		
		public $pageSize = 50;
		protected $smarty;
		protected $userinfo;
		protected $groupinfo;
		protected $menu;
		protected $actionName;
		protected $methodName;
		protected $actionKey;
        protected $iplimit = 0;

		//需要隐藏用户名的渠道
		protected $display_username_channelids = array();

		protected $allowedAccess = array(
			'userlogin',
			'userlogin/Login',
            'userlogin/LoginByPhone',
            'userlogin/LoginByToken',
			'userlogin/Index',
			'userlogin/Loginout',
			'userlogin/Verify',
            'userlogin/SendSMS',
		);

		//不需要IP限制的方法
		protected $noIpLimit = array(
            'userlogin',
            'userlogin/Login',
            'userlogin/LoginByPhone',
            'userlogin/LoginByToken',
            'userlogin/Index',
            'userlogin/Loginout',
            'userlogin/Verify',
            'userlogin/SendSMS',
            'home/Notice',
            'home/Noticelist',
            'home/NoticeDetail',
            'platform/Index'
        );

		// 权限链用以验证ajax是否处于当前页面下
		private static $authChains = array(
            'userproperty/index' => array('setcols'),
		);

		//管理员账号配置
        public $adminuserids = array(2815246,500278201,502048209,504041619,2815246,504143598,504143643,504146353,504185046);//正式线

        public static $menuadminids = array();

		public function __construct(){
			$this->init();

			if(!in_array($this->actionKey,$this->noIpLimit)) {
                $ip = AppCommon::getUserIP();
                $isIplimit = CommonUtil::checkIpLimit($ip);
                $this->iplimit = $isIplimit ? 1 : 0;
            }

			// ajax请求分发
			if (isset($_REQUEST['mode']) && strtolower($_REQUEST['mode']) == 'ajax' && isset($_REQUEST['action']) && !empty($_REQUEST['action'])) {
            	$this->_ajaxAction($_REQUEST['action']);
			}
		}
		
		public function init(){
			$this->smarty = AppHelper::GetSmarty();
			$action = isset($_REQUEST['r']) && $_REQUEST['r'] ? $_REQUEST['r'] : '';
			$group = isset($_REQUEST['g']) && $_REQUEST['g'] ? $_REQUEST['g'] : '';
			$this->userinfo = Common::getUserInfo(false, LOGIN_SECURE_FRONT_KEY);

			
			$uri = explode('/', $action);
			// 站点配置信息
			$this->smarty->assign('siteLogo', SITE_LOGO);
			$this->smarty->assign('siteName', SITE_NAME);
			$this->smarty->assign('action', $uri[0]);

			$role=0;
			if($action == 'userlogin' || $action == 'userlogin/index' || $action == 'userlogin/login' || $action == 'userlogin/verify' || $action == 'userlogin/loginByPhone' || $action == 'userlogin/sendSMS' || $action == 'userlogin/loginByToken'){
				// 登录页面处理，有session则跳入后台
				if(!empty($this->userinfo)){
					header('Location:?r=home');
				}
			}else{
				// 不是登录页，session过期则跳到登录页
                if(empty($this->userinfo) || empty($this->userinfo['userid'])){
                    PageFormat::send(false, '请先登录!', "?r=userlogin", false, true);
                }

                $role = $this->userinfo['level'];
//                if($this->userinfo['is_cdian'] != 1){
//                    Common::clearLoginInfo(LOGIN_SECURE_FRONT_KEY);
//                    PageFormat::send(false, '该用户没有权限登录！', "?r=userlogin", false, true);
//                }
			}



            $this->userinfo['userRole'] = $role;
			$this->smarty->assign('account', $this->userinfo['account']);
			$this->smarty->assign('user', $this->userinfo);

			$param = explode('/', $action);
			$this->actionName = $actionName = isset($param[0]) ? lcfirst($param[0]) : '';
			$this->methodName = $methodName = isset($param[1]) ? ucfirst($param[1]) : 'Index';
			$this->actionKey = $action_key = $actionName.'/'.$methodName;

			// 免权限验证动作
			if(in_array($action_key, $this->allowedAccess)){
				return true;
			}

			//获取用户扩展信息[go币，渠道号]
//			$this->getUserExt();

			// 查询该动作的menuid
			$menuModule = new AdminModule();
			$this->menu = $menuModule->getMenuByKey($action_key);

			// 记录管理员操作日志，登录，首页访问信息不做记录
			$this->operationLog();

			//加载顶部导航
			$this->buildTopMenuList();

			// 超级管理员免权限验证

			if($role == 1){
				//初始化导航菜单
				$navList = $this->getMenuList();
				$this->smarty->assign('navlist', $navList);
				return true;
			}
			if(empty($this->menu)){
				PageFormat::send(false, '操作项不存在，请与管理员联系!', "?r=userlogin", false, true);
			}
			// 验证action执行权限
			$this->userinfo['priv'] = AdminService::getUserPrivArray($this->userinfo['userid']);

			if(! in_array($this->menu['menuid'], $this->userinfo['priv'])){
				PageFormat::send(false, '您无权操作此项，请与管理员联系!', "?r=userlogin", false, true);
			}
			//初始化导航菜单
			$navList = $this->getMenuList();
			$this->smarty->assign('navlist', $navList);
            $this->smarty->assign('CONFIG_DEFINE', Main::$config['define']);
		}

		
		/**
		 * 判断登录
		 */
		public function checkLogin(){
			$login_flag = false;
			$this->userinfo = Common::getUserInfo(false, LOGIN_SECURE_FRONT_KEY);
		
			if(! empty($this->userinfo)){
				$this->smarty->assign('account', $this->userinfo['account']);
				$login_flag = true;
			}
		
			return $login_flag;
		}
		
		/**
		 * 检查管理员的数据操作权限
		 * @param string $action_key
		 * @return boolean
		 */
		public function checkDataPriv($action_key){
			$flag = false;
			if($action_key){
				// 查询该动作的menuid
				$menuModule = new BmAdminModule();
				$data_priv = $menuModule->getMenuByKey($action_key);
				
				if($data_priv){
					if(in_array($data_priv['menuid'], $this->userinfo['priv'])){
						$flag = true;
					}
				}
			}
			return $flag;
		}
		public function display($template = null, $cache_id = null, $compile_id = null, $parent = null){
			$this->smarty->display($template, $cache_id, $compile_id, $parent);
		}
		public function assign($tpl_var, $value = null, $nocache = false){
			$this->smarty->assign($tpl_var, $value, $nocache);
		}
		public function redirect($url, $msg = '', $istop = false){
			AppCommon::redirect($url, $msg, $istop);
		}
		
		/**
		 * Ajax方式返回数据到客户端
		 * 
		 * @access protected
		 * @param mixed $data 要返回的数据
		 * @param int $code 状态
		 * @param string 信息
		 * @param String $type AJAX返回数据格式
		 * @return void
		 */
		protected function ajaxReturn($returndata, $code = 0, $msg = '', $type = ''){
			$data['code'] = $code;
			$data['message'] = $msg;
			$data['data'] = $returndata;
			
			if(empty($type))
				$type = 'JSON';
			switch(strtoupper($type)){
				case 'JSON':
					// 返回JSON数据格式到客户端 包含状态信息
					header('Content-Type:application/json; charset=utf-8');
					exit(json_encode($data));
				case 'XML':
					// 返回xml格式数据
					header('Content-Type:text/xml; charset=utf-8');
				// exit(xml_encode($data));
				case 'EVAL':
					// 返回可执行的js脚本
					header('Content-Type:text/html; charset=utf-8');
					exit($data);
				default:
					// 返回可执行的js脚本
					header('Content-Type:text/html; charset=utf-8');
					exit($data);
			}
		}
		
		/**
		 * [error 失败返回]
		 * @param  [string]  $message [description]
		 * @param  [mixed] $waittime    [是否跳转，如需跳转请传正整数，代表跳转等待秒数]
		 * @param  [string]  $jumpUrl [description]
		 * @return [type]           [description]
		 */
		public function error($message = '', $waittime = false, $jumpUrl = '') {
			$jumpUrl = empty($jumpUrl)?$_SERVER["HTTP_REFERER"]:$jumpUrl;
			$message = empty($message)?'操作失败':$message;
			if ($waittime > 0) {
				$this->assign('waittime', $waittime);
				$this->assign('message', $message);
				$this->assign('jumpUrl', $jumpUrl);
				$this->assign('code', 400);
				$this->display('dispatch_jump.html');
			}else {
				$return = array(
					'code' => 400,
					'message' => $message,
					'data' => $jumpUrl?array('jumpUrl'=>$jumpUrl):null
				);
				return $return;
			}
		}

		/**
		 * [success 成功返回]
		 * @param  [type]  $data     [description]
		 * @param  [mixed] $waittime [是否跳转，如需跳转请传正整数，代表跳转等待秒数]
		 * @param  [string]  $message  [description]
		 * @param  [string]  $jumpUrl  [description]
		 * @return [type]            [description]
		 */
		public function success($data = null, $waittime = false, $message = '', $jumpUrl = '') {
			$jumpUrl = empty($jumpUrl)?$_SERVER["HTTP_REFERER"]:$jumpUrl;
			$message = empty($message)?'操作成功':$message;
			if ($waittime > 0) {
				$this->assign('waittime', $waittime);
				$this->assign('message', $message);
				$this->assign('jumpUrl', $jumpUrl);
				$this->assign('code', 200);
				$this->display('dispatch_jump.html');
			}else {
				$return = array(
					'code' => 200,
					'message' => $message,
					'data' => $data
				);
				return $return;
			}
		}
		
		/**
		 * 管理员操作记录
		 * @status string 操作是否成功
		 * @admin_name string 管理员
		 */
		public function operationLog(){
			// 操作id
			$menuid = isset($this->menu['menuid']) ? $this->menu['menuid'] : 0;
			// 操作访问路径
			$route = $_SERVER['SCRIPT_NAME'] . $_SERVER['REQUEST_URI'];
			// 获取操作参数列表
			$method = $_SERVER['REQUEST_METHOD'];
			$params = $method == 'GET' ? json_encode($_GET) : json_encode($_POST);
			
			// 登录ip
			$ip = AppCommon::getUserIP();
			// 用户ID
			$userid = $this->userinfo['userid'];

			$model = new OperationModule();
			$model->log($menuid, $route, $ip, $userid, $params);
		}
		
		private function getMenuList() {
			$result = array();

			$userinfo = $this->userinfo;
			$action = isset($_REQUEST['r']) && $_REQUEST['r'] ? $_REQUEST['r'] : '';
			$param = explode('/', $action);
			$actionName = isset($param[0]) ? $param[0] : '';
			$methodName = isset($param[1]) ? $param[1] : 'index';
			$action_key = $actionName.'/'.$methodName;

			if(! empty($userinfo)){
				//查询菜单数据
				$menuModule = new AdminModule();
				//取出所有的列表
				$menu = $menuModule->getAllMenu('*', - 1, 1);
				//查询管理员权限,超级管理员拥有全部菜单管理权限
				$purview = array();
				if($userinfo['userRole'] == UserUtil::ROLE_1){
					foreach($menu as $value){
						array_push($purview, $value['menuid']);
					}
				}else{
					$purview = $userinfo['priv'];
				}

				if(!empty($purview)){
					foreach($menu as $val){
						//是否选中
						$val['selected'] = 0;
						if (strtolower($action_key) == strtolower($val['action_key'])) {
							$val['selected'] = 1;
						}

						if(in_array($val["menuid"], $purview)){
							$result[intval($val['parentid'])][] = $val;
						}
					}
				}
			}

            //指定菜单权限
            $menuadminids = self::$menuadminids;
            if (isset($menuadminids[$userinfo['btgouserid']])){
                foreach ($result as $parentid=>$menuList){
                    if ($parentid==0){
                        foreach ($menuList as $k=>$item){
                            if (!in_array($item['menuid'],$menuadminids[$userinfo['btgouserid']])){
                                unset($result[$parentid][$k]);
                            }
                        }
                    }
                }
            }

			return $result;
		}

		//顶部菜单
		private function buildTopMenuList() {
			$result = array();

			/*if (UserService::checkUpdatePhoneEnable($this->userinfo['id'])) {
				$result[] = '<span><span class=""></span><a href="?r=userchannel/modifyPhone">修改手机</a></span>';
			}*/

			$this->smarty->assign('topMenuList', $result);
		}

		/**
		 * [_ajaxAction ajax请求分发]
		 * @param  [type] $action [description]
		 * @return [type]         [description]
		 */
		protected function _ajaxAction($action) {
			$action = strtolower($action);
			$r = strtolower($_REQUEST['r']);

			if ($this->userinfo['userRole'] != UserUtil::ROLE_1 && (!isset(self::$authChains[$r]) || !in_array($action, self::$authChains[$r]))) {
				exit(json_encode($this->error('非法请求')));
			}elseif (!empty($action) && method_exists($this, $action)) {
				$result = $this->$action();
				$this->clearNull($result);
				exit(json_encode($result));
			}else {
				exit(json_encode($this->error('非法请求')));
			}
		}

		/**
		 * [pageFormat 分页返回]
		 * @param  [type] $data  [description]
		 * @param  [type] $total [description]
		 * @return [type]        [description]
		 */
		public function pageFormat($data, $total, $page = 1, $pagesize = 10) {
			$data = array(
				'rows' => $data,
				'total' => $total,
				'page' => $page,
				'pagesize' => $pagesize,
				'maxpage' => ceil($total/$pagesize)
			);
			return json_encode($data);
		}
		
		public function clearNull(&$result, $key = 'rows'){
			if(!isset($result[$key]) || empty($result[$key]) || !is_array($result[$key])){
				return;
			}
			foreach($result[$key] as &$v){
				foreach($v as &$v1){
					if($v1 === null){
						$v1 = '';
					}
				}
			}
			unset($v);
		}


        protected function isPost(){
            return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'POST');
        }

    /**
     * 隐藏字符串
     * $str 字符串
     * $num 保留前后X位
     */
    protected function hide_str($str, $num = 2){
        if (empty($str)) {
            return $str;
        }
        $len = mb_strlen($str);
        //手机号
        if ($len == 11 && is_numeric($str)) {
            return substr_replace($str, '****', 3, 4);
        }
        if ($len > 5) {
            $str1 = mb_substr($str, 0, $num, 'utf-8');
            $str2 = mb_substr($str, $len - $num, $num, 'utf-8');
            $leftLen = $len - ($num * 2);
            $hideStr = str_pad('*', $leftLen, "*", STR_PAD_LEFT);
            return $str1 . $hideStr . $str2;
        } else {
            $str1 = mb_substr($str, 0, 1, 'utf-8');
            $str2 = mb_substr($str, $len - 1, 1, 'utf-8');
            return $str1 . '**' . $str2;
        }
    }
}
